import _ from 'lodash'
import undoable from 'redux-undo'
import {createReducer} from 'restack-core'

const findRecord = (list,id) => {
  return _.find(list, function(item){
    return +id == item.id
  })
}

const ADD_TODO = "todo.ADD"
const TOGGLE_TODO = "todo.TOGGLE"

var todos = createReducer([],{
  [ADD_TODO](state,action){
     return [...state,{
        id: action.id,
        text: action.text,
        completed: false
      }]
  },
  [TOGGLE_TODO](state,action){
    let id = action.id,
        result = findRecord(state,id),
        length = state.length
    console.log(result)
    return [...state.slice(0,id),
            {
              id:result.id,
              text:result.text,
              completed:!result.completed
            },
            ...state.slice(id+1,length)]
  }
})
todos = undoable(todos)


const todo = {
  name: 'todo',
  initialState: {
    todos:[]
  },
  sagas: {
    *adds(action, {update, put, call}) {
      console.log(action.payload.num)
      yield update({num:action.payload.num})

      // yield put({ type: "crudModules.REQUES T", payload: {isFetching: true} })
      const response = yield call(fetch, `/system/api/v1/modules`)
      if (response) {
        yield put({type: "crudModules.SUCCESS", response});
        // yield put({type: "crudModules.SUCCESS", Object.assign({})})
      } else {
        yield put({type: "crudModules.FAILURE", error})
      }
    },
    *add(action, {update, put, select ,call}) {
      var newTodos = yield select((state)=>{
        return ([...state.todo.todos,{
                  id: action.payload.id,
                  text: action.payload.data,
                  completed: false
                 }])
      })

      yield update({type: ADD_TODO,todos:newTodos})
    },
    *toggle(action, {update, put, select ,call}) {
      console.log(action.payload.id)
      var len = action.payload.length,
          id = action.payload.id
      var result = yield select((state)=>{
        console.log(state)
        var aaa = findRecord(state.todo.todos,id)
        return(aaa)
      })
      var newTodoss = yield select((state)=>{
        return ([...state.todo.todos.slice(0,id),{
                  id: result.id,
                  text: result.text,
                  completed: !result.completed
                },
      ...state.todo.todos.slice(id+1,len)])
      })
      yield update({todos:newTodoss})
    },
    *update() {

    },
    *fetch() {
      yield console.log("fetching list");
    },
    *destroy() {

    }
  }
}
export default todo

export {todos}
